package com.example.projects;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;

public class MyFacebook {
        private static Facebook facebook;
        private static CPT3004 app = null;
        private static SharedPreferences mPrefs;
        private static AsyncFacebookRunner mAsyncRunner;
        
        public static void loginToFacebook(Activity act) {
                app = (CPT3004)act.getApplication();
                int activityCode = 0;
                // get facebook
                facebook = app.getFacebook();

        // check for valid session
                if (!facebook.isSessionValid()) { 
                        String[] permissions = {};
                        
                        // authorize activity with facebook
                        facebook.authorize(act, permissions, activityCode,
                                        new DialogListener() {

                                        @Override
                                        public void onCancel() {
                                                System.out.println("Facebook Canceled");
                                                // Function to handle cancel event
                                        }

                                        @Override
                                        public void onComplete(Bundle values) {
                                                // Function to handle complete event
                                                // Edit Preferences and update facebook acess_token
                                                mPrefs = app.getSharedPreferences("", Context.MODE_PRIVATE);
                                                SharedPreferences.Editor editor = mPrefs.edit();
                                                editor.putString("access_token",
                                                                facebook.getAccessToken());
                                                editor.putLong("access_expires",
                                                                facebook.getAccessExpires());
                                                editor.commit();
                                                // Now have valid session so set name and id
                                                setUsernameID(app);
                                                System.out.println("OnComplete login access token " +mPrefs.getString("access_token", null));
                                        }

                                        @Override
                                        public void onError(DialogError error) {
                                                System.out.println("Login DialogError");
                                                error.printStackTrace();
                                                // Function to handle error
                                        }

                                        @Override
                                        public void onFacebookError(FacebookError fberror) {
                                                fberror.printStackTrace();
                                                // Function to handle Facebook errors
                                                System.out.println("Facebook Error");
                                        }

                                });
                }else {
                        // session is valid set name and id
                        setUsernameID(app);
                }
        }
        
        public static void setUsernameID(CPT3004 ap) {
                app = ap;
                facebook = app.getFacebook();
                if(facebook.getAccessToken() != null) {
                        mAsyncRunner = new AsyncFacebookRunner(facebook);
                        mAsyncRunner.request("me", new RequestListener() {
                                @Override
                                public void onComplete(String response, Object state) {
                                        Log.d("Profile", response);
                                        String json = response;
                                        try {
                                                // Facebook Profile JSON data
                                                JSONObject profile = new JSONObject(json);
                                                
                                                // set userID from facebook
                                                app.setFBID(profile.getString("id"));
                                                // set username from facebook
                                                app.setFBName(profile.getString("name"));
                                                
                                        } catch (JSONException e) {
                                                System.out.println("GetProfileInformation JSON exception: access token " +facebook.getAccessToken());
                                                e.printStackTrace();
                                        }
                                }
        
                                @Override
                                public void onIOException(IOException e, Object state) {
                                        System.out.println("GetProfileInformation IOException");
                                        e.printStackTrace();
                                }
        
                                @Override
                                public void onFileNotFoundException(FileNotFoundException e,
                                                Object state) {
                                        System.out.println("GetProfileInformation FileNotFoundException");
                                        e.printStackTrace();
                                }
        
                                @Override
                                public void onMalformedURLException(MalformedURLException e,
                                                Object state) {
                                        System.out.println("GetProfileInformation MalformedURLException");
                                        e.printStackTrace();
                                }
        
                                @Override
                                public void onFacebookError(FacebookError e, Object state) {
                                        System.out.println("GetProfileInformation FacebookError");
                                        e.printStackTrace();
                                }
                        });
                }
        }
    
        /**
         * Function to Logout user from Facebook
         * NEVER logout without first logging in
         * */
        public static void logoutFromFacebook(Context context, CPT3004 ap) {
                app = ap;
                // get facebook
                facebook = app.getFacebook();
                
                // perform the logout asynchronously
                mAsyncRunner = new AsyncFacebookRunner(facebook);
                mAsyncRunner.logout(context, new RequestListener() {
                        @Override
                        public void onComplete(String response, Object state) {
                                Log.d("Logout from Facebook", response);
                                if (Boolean.parseBoolean(response) == true) {
                                        // delete stored access token if logout successful
                                        mPrefs = app.getSharedPreferences("", Context.MODE_PRIVATE);
                                        SharedPreferences.Editor editor = mPrefs.edit();
                                        editor.remove("access_token");
                                        editor.remove("access_expires");
                                        editor.commit();
                                        // remove username and id
                                        app.setFBName(null);
                                        app.setFBID(null);
                                        System.out.println("facebook successfully logged out =]");
                                }
                        }

                        @Override
                        public void onIOException(IOException e, Object state) {
                                System.out.println("Logout IOException");
                                e.printStackTrace();
                        }

                        @Override
                        public void onFileNotFoundException(FileNotFoundException e,
                                        Object state) {
                                System.out.println("Logout FileNotFoundException");
                                e.printStackTrace();
                        }

                        @Override
                        public void onMalformedURLException(MalformedURLException e,
                                        Object state) {
                                System.out.println("Logout MalformedURLException");
                                e.printStackTrace();
                        }

                        @Override
                        public void onFacebookError(FacebookError e, Object state) {
                                System.out.println("Logout FacebookError");
                                e.printStackTrace();
                        }
                });
        }

}